package org.vectrics.client.framework;



import javax.swing.JFrame;
import javax.swing.UIManager;
import java.awt.*;
import java.io.PrintWriter;

import org.apache.log4j.*;
import org.vectrics.VectricsException;
import java.util.*;

import org.vectrics.client.webclient.CommandDispatcher;
import org.vectrics.client.module.ModuleManager;
import org.vectrics.swing.GuiManager;

//import com.jgoodies.looks.plastic.PlasticLookAndFeel;

import javax.swing.SwingUtilities;




public class Main {
    private transient static Logger log = Logger.getLogger(Main.class);
    boolean packFrame = false;
   // private String STYLE_CLASS = "com.incors.plaf.kunststoff.KunststoffLookAndFeel";
   // private String STYLE_NAME = "Kunststoff";
    private String configFile = "vectrics-client.xml";
    
    
    /**
     * Construct the main application class.
     */
    public Main() throws VectricsException {
    }

    
    protected void execute() throws VectricsException {
        
        ClientConfiguration configuration = null;
		try {
			configuration = loadConfiguration(configFile);
		}
		catch (VectricsException ve) {
			log.error("VectricsException loading configuration", ve);
			throw new VectricsException("VectricsException loading configuration");
		}
		log.info("Initializing application");
		configuration.getApplication().initialize(false);
		log.info("Creating dispatcher");
		CommandDispatcher dispatcher = configuration.getApplication().createDispatcher();
		log.info("Setting dispatcher connection");
		dispatcher.setConnection(configuration.getConnection());
		configuration.getApplication().setDispatcherProperties(dispatcher);
		
		

        log.debug("creating ClientFrame instance");
        ClientFrame frame = new ClientFrame(configuration);
        ErrorFrame.intitialize(frame);
        changeStyle(frame);
        	

        log.debug("packing or validating frame");
        if (packFrame) {
          frame.pack();
        }
        else {
          frame.validate();
        }

        if (configuration.getDefaultModule() != null) {
        	ModuleManager.getInstance().showModule(configuration.getDefaultModule());
        }
        
        log.debug("centering the window");
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = frame.getSize();
        
        if (frameSize.height > screenSize.height) {
          frameSize.height = screenSize.height;
        }
        
        if (frameSize.width > screenSize.width) {
          frameSize.width = screenSize.width;
        }
        
        frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);

        log.info("making main form visible");
        frame.setVisible(true);
        
        log.info("done with setup");
    }


	private ClientConfiguration loadConfiguration(String fileName) throws VectricsException {
		if (fileName == null)
			throw new VectricsException("Attempt to load configuration without specifying a filename");
		ClientConfiguration config = null;
		try {
			config = new ClientConfiguration(fileName);
		}
		catch (Exception ex) {
			log.error("Exception reading configuration file", ex);
			throw new VectricsException("Exception reading configuration file", ex);
		}
		return(config);
	}


	/** Change the style of the application */
	public void changeStyle(JFrame frame) {

		
		frame.setFont(GuiManager.getInstance().getStandardFont());
		try {
//	        PlasticLookAndFeel.setMyCurrentTheme(PlasticLookAndFeel.createMyDefaultTheme());
//	        PlasticLookAndFeel.setTabStyle(PlasticLookAndFeel.TAB_STYLE_DEFAULT_VALUE);
//	        PlasticLookAndFeel.setHighContrastFocusColorsEnabled(true);
//
//	        UIManager.setLookAndFeel(new PlasticLookAndFeel());
			SwingUtilities.updateComponentTreeUI(frame);
		} catch (Exception e) {
			log.error("Couldn't set default look and feel", e);
			try{
				UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
				SwingUtilities.updateComponentTreeUI(frame);
				//styleClass = "javax.swing.plaf.metal.MetalLookAndFeel";
				//styleName = "Metal";
			}
			catch (Exception ex) {
				log.error("Exception setting look and feel", ex);
			}
		}
		/*
		try {	
			// Change the font style of menu, button ...
			MetalLookAndFeel c = (MetalLookAndFeel)Class.forName(styleClass).newInstance();
			MetalLookAndFeel.setCurrentTheme(new VectricsTheme());
		} 
		catch(Exception e) {
			log.error("Exception setting theme", e);
		}
		*/
	}

	public static void initLogging() {
		BasicConfigurator.configure();
		Logger root = LogManager.getRootLogger();
		
		log.debug("instantiating GuiManager to handle creating standard swing components and appearance");
		
		Enumeration appenders = root.getAllAppenders();
		root.removeAllAppenders();
		ConsoleAppender appender = new ConsoleAppender();
		PrintWriter writer = new PrintWriter(System.out);
		appender.setWriter(writer);
		appender.setThreshold(Level.DEBUG);
		PatternLayout layout = new PatternLayout("%-6r [%9.9t] %-5p %40.40c %x - %m\n");
		appender.setLayout(layout);
		root.addAppender(appender);
		
		root.setLevel(Level.INFO);
	}

	
	public static void main(String[] args) {
		
		try {
			initLogging();
			String configFileName = null;
			if (args.length > 0) {
				configFileName = args[0];
				log.info("Vectrics configuration file: " + configFileName);
			}
			Main theMain = new Main();
			if (configFileName != null)
				theMain.setConfigFile(configFileName);
			theMain.execute();
		}
		catch (VectricsException ve) {
			log.error("Exception running application", ve);
			System.exit(-1);
		}
  }
  
  
	/**
	 * @return Returns the configFile.
	 */
	public String getConfigFile() {
		return configFile;
	}

	/**
	 * @param configFile The configFile to set.
	 */
	public void setConfigFile(String configFile) {
		this.configFile = configFile;
	}

}